package org.jeecg.modules.zhoupackage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.modules.degression.mapper.MlccPriceSystemPingleiMapper;
import org.jeecg.modules.degression.mapper.MyMlccPriceSystemCostRecordMapper;
import org.jeecg.modules.degression.pojo.MlccPriceSystemCostRecord;
import org.jeecg.modules.degression.pojo.MlccPriceSystemPinglei;
import org.jeecg.modules.gwcjava.jiekou.entity.MlccUserInfo;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.pojo.MlccThirdGoods;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyErrorOrderMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccCompanyInfoMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccCompanyInfo;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccErrorOrder;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.service.IOrderCenterService;
import org.jeecg.modules.zhoupackage.GoodsOrder.mapper.MyMlccThirdGoodsOrderMapper;
import org.jeecg.modules.zhoupackage.GoodsOrder.pojo.MlccThirdGoodsOrder;
import org.jeecg.modules.zhoupackage.mapper.*;
import org.jeecg.modules.zhoupackage.pojo.*;
import org.jeecg.modules.zhoupackage.pojo.myexcel.SingOrderExcel;
import org.jeecg.modules.zhoupackage.pojo.myexcel.TeamOrderExcel;
import org.jeecg.modules.zhoupackage.service.ICartService;
import org.jeecg.modules.zhoupackage.service.IOrderService;
import org.jeecg.modules.zhoupackage.util.FabricUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 面料下单Service
 *
 * @author zxl
 * @since 20200923
 */
@SuppressWarnings("all")
@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    ICartService service;

    @Autowired
    IOrderCenterService orderService;

    @Autowired
    MyMlccFabricOrderinfoMapper mapper;

    @Autowired
    MyMlccBusinessWaterInfoMapper businessWaterInfoMapper;

    @Autowired
    MlccCartInfoMapper cartInfoMapper;

    @Autowired
    CartMlccUserInfoMapper userInfoMapper;

    @Autowired
    MlccFabricInfoMapper fabricInfoMapper;

    @Autowired
    FabricUtil fabricUtil;

    @Autowired
    MlccGroupInfoMapper groupInfoMapper;

    @Autowired
    MyMapper myMapper;

    @Autowired
    MyMlccModuleSmallTemplateMapper moduleSmallTemplateMapper;

    @Autowired
    MyMlccCategoryInfoMapper categoryInfoMapper;

    @Autowired
    MyMlccSingleOrderInfoMapper singleOrderInfoMapper;

    @Autowired
    MyMlccAafterSalesinfoMapper afterSalesinfoMapper;

    @Autowired
    MyTeamOrderMapper teamOrderMapper;

    @Autowired
    MyMlccFabricOrderinfoMapper fabricOrderinfoMapper;

    @Autowired
    MyExcelMapper excelMapper;

    @Autowired
    MyProductBodySizeMapper productBodySizeMapper;

    @Autowired
    MyMlccReoairMapper reoairMapper;

    @Autowired
    TeamOrderAafterTMapper selectEmpMapper;

    @Autowired
    MyDepartProductMapper departProductMapper;

    @Autowired
    MyMlccProductInfoMapper productInfoMapper;

    @Autowired
    MyBodySizeMapper bodySizeMapper;

    @Autowired
    MyTrackingOrderMapper trackingOrderMapper;

    @Autowired
    MyMlcctrackingProductMapper trackingProductMapper;

    @Autowired
    MyMlccFanxiuMapper fanxiuMapper;

    @Autowired
    TeamOrderAafterTMapper orderAafterTMapper;

    @Autowired
    MyMlccPriceSystemCostRecordMapper recordMapper;

    @Autowired
    MlccPriceSystemPingleiMapper priceSystemPingleiMapper;

    @Autowired
    MyMlccEventRecrodInfoMapper eventRecrodInfoMapper;

    @Autowired
    MyErrorOrderMapper errorOrderMapper;

    @Autowired
    MyMlccstoreMapper storeMapper;

    @Autowired
    MyMlccCompanyInfoMapper companyInfoMapper;

    @Autowired
    MyMlccThirdGoodsOrderMapper goodsOrderMapper;

    /**
     * 创建未支付的面料订单
     *
     * @param token 令牌
     * @param order 订单类
     * @return 返回的是订单ID
     */
    @Override
    @Transactional
    public String createFabricOrder(String token, MlccFabricOrderinfo order) {
        if (!fabricUtil.checkToken(token)) return "-1"; // token错咯
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        System.out.println("orgcode===========" + userDetail.getOrgCode());
        // 设置订单实体类基本信息
        // 创建一个随机数
        Random random = new Random();
        int i = random.nextInt(9999);
        order.setUserId(userDetail.getId() + "").setOrderSn("F" + System.currentTimeMillis() + i).setStatus(0).setSysOrgCode(userDetail.getOrgCode())
                .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
        /*获取订单总金额*/
        BigDecimal totalAmount = new BigDecimal(0);
        String[] cartids = order.getCartId().split(",");
        for (String cartid : cartids) {
            try {
                double lastDiscount = 1;
                // 获取购物车基本信息
                MlccCartInfo mlccCartInfo = cartInfoMapper.selectById(cartid);
                // 获取面料ID
                String fabricId = mlccCartInfo.getFabricId();
                MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(fabricId);
                // 获取购买数量
                double buyNumber = mlccCartInfo.getBuyNumber();

                // 计算订单总金额（每个购物车的金额相加）
                totalAmount = totalAmount.add(new BigDecimal(Double.valueOf(mlccCartInfo.getTotalAmount())));
            } catch (Exception e) {
                return "-6";/*购物车已被清空，请勿重复支付*/
            }
        }
        //设置订单价格
        order.setOrderMoney(totalAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        int insert = mapper.insert(order);
        if (insert > 0) { // 添加成功之后需要改变购物车的状态
            System.out.println("订单编号是多少？" + order.getOrderSn());
            for (String cartid : cartids) {
                MlccCartInfo cartInfo = cartInfoMapper.selectById(cartid);
                cartInfo.setStatus(2);
                cartInfoMapper.updateById(cartInfo);
            }
            // 往订单流水表添加数据
            MlccBusinessWaterInfo wrater = new MlccBusinessWaterInfo();
            wrater.setOrderId(order.getId() + "").setType(0).setUserId(userDetail.getId() + "")
                    .setCostMoney(order.getOrderMoney()).setYewuInstructions("正常订单，前端提交面料订单")
                    .setYewuDeatil("提交订单").setStatus(0).setRemark("面料下单提交订单，生成未支付面料订单")
                    .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername())
                    .setSysOrgCode(userDetail.getOrgCode())
                    .setOrderSn(order.getOrderSn()).setStoreId(order.getStoreId()).setId(UUID.randomUUID().toString().substring(0, 15));
            businessWaterInfoMapper.insert(wrater);

            // 2、往订单跟踪表添加一条记录
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setId(UUID.randomUUID().toString().substring(0, 15)).setOrderSn(order.getOrderSn())
                    .setOrderType(0).setThing("创建订单").setCreateBy(userDetail.getUsername())
                    .setUpdateBy(userDetail.getUsername()).setRemark("前端提交的订单");
            trackingOrderMapper.insert(trackingOrder);
            return order.getOrderSn();
        } else {
            return "0";
        }
    }

    /**
     * 获取用户订单列表
     *
     * @param token     令牌
     * @param orderType 0:个订  1:团体  2:成衣  3:面料
     */
    @Override
    public JSONObject getOrderList(int pageNo, int pageSize, String token, int orderType, String time, String endtime,
                                   Integer status, String code, String fabricCode, String emp, String cusname, String companyName) {
        JSONObject result = new JSONObject();
        /*对token的校验*/
        if (!fabricUtil.checkToken(token)) {
            result.put("code", "1");
            result.put("msg", "token失效");
            return result;
        }
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        String companyOrgcode = userDetail.getCompanyOrgcode();
        /*如果是面料订单*/
        if (orderType == 3) {
            try {
                Page<MyOrderEntity> page = new Page<>(pageNo, pageSize);
                IPage<MyOrderEntity> orderList = fabricUtil.getFabricOrderList(page, token, time, endtime, status, code, fabricCode, emp, cusname);
                List<MyOrderEntity> records = orderList.getRecords();
                if (records != null && records.size() > 0) {
                    // 给每条订单查询门店与下单员工
                    records.stream().forEach(single -> {
                        MlccStoreInfo storeInfo = storeMapper.selectById(single.getStoreId());
                        if (storeInfo != null) {
                            single.setStoreName(storeInfo.getStoreName());
                        }
                        // 查询下单员工
                        MlccUserInfo userInfo = userInfoMapper.selectById(single.getUserId());
                        if (userInfo != null) {
                            single.setEmpName(userInfo.getRealname());
                        }
                    });
                }
                result.put("data", orderList);
                result.put("code", 0);
                result.put("msg", "查询成功");
            } catch (Exception e) {
                e.printStackTrace();
                result.put("code", 1);
                result.put("msg", "查询失败");
            }
            return result;
            /*如果是个订订单*/
        } else if (orderType == 0) {
            Page<MlccSingleOrderInfo> page = new Page<>(pageNo, pageSize);
            IPage<MlccSingleOrderInfo> singleOrderList = fabricUtil.getSingleOrderList(page, userDetail.getId(), token, time, endtime, status, code, cusname, emp);
            List<MlccSingleOrderInfo> records = singleOrderList.getRecords();
            if (records != null && records.size() > 0) {
                // 给每条订单查询门店与下单员工
                records.stream().forEach(single -> {
                    QueryWrapper<MlccStoreInfo> storeWwrapper = new QueryWrapper<>();
                    storeWwrapper.eq("store_code", single.getStoreId());
                    MlccStoreInfo storeInfo = storeMapper.selectOne(storeWwrapper);
                    if (storeInfo != null) {
                        single.setStoreName(storeInfo.getStoreName());
                    }
                    // 查询下单员工
                    MlccUserInfo userInfo = userInfoMapper.selectById(single.getUserId());
                    if (userInfo != null) {
                        single.setEmpName(userInfo.getRealname());
                    }
                });
            }

            result.put("data", singleOrderList);
            result.put("code", 0);
            result.put("msg", "查询成功");
        } else if (orderType == 1) {
            /*如果是团订*/
            Page<MlccTeamOrderInfo> page = new Page<>(pageNo, pageSize);
            IPage<MlccTeamOrderInfo> teamOrderList = fabricUtil.getTeamOrderList(page, userDetail.getId(), token, time, endtime, status, code, companyName, emp);
            List<MlccTeamOrderInfo> records = teamOrderList.getRecords();
            if (records != null && records.size() > 0) {

                // 给每条订单查询门店与下单员工
                records.stream().forEach(single -> {
                    MlccStoreInfo storeInfo = storeMapper.selectById(single.getStoreId());
                    if (storeInfo != null) {
                        single.setStoreName(storeInfo.getStoreName());
                    }
                    // 查询下单员工
                    MlccUserInfo userInfo = userInfoMapper.selectById(single.getUserId());
                    if (userInfo != null) {
                        single.setEmpName(userInfo.getRealname());
                    }
                });
            }
            result.put("data", teamOrderList);
            result.put("code", 0);
            result.put("msg", "查询成功");
        } else if (orderType == 2) {
            // 现货订单
            Page<MlccThirdGoodsOrder> page = new Page<>(pageNo, pageSize);
            IPage<MlccThirdGoodsOrder> orderList = fabricUtil.getGoodsOrderList(page, userDetail.getId(), token, time, endtime, status, code);
            result.put("data", orderList);
            result.put("code", 0);
            result.put("msg", "查询成功");
        }
        return result;
    }

    /**
     * 根据订单id获取面料订单详情
     *
     * @param token         令牌
     * @param fabricOrderId 面料订单ID
     */
    @Override
    public List<CartEntity> getFabricOrderList(String token, int fabricOrderId) {
        if (!fabricUtil.checkToken(token)) return null;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        // 面料订单基本信息
        MlccFabricOrderinfo orderinfo = mapper.selectById(fabricOrderId);
        if (orderinfo == null) return null;
        // 购物车ids
        String cartId = orderinfo.getCartId();
        String[] ids = cartId.split(",");
        List<String> oerderCartId = Arrays.asList(ids);
        // 查到了所有的购物车
        List<CartEntity> farbicOrderList = cartInfoMapper.getFarbicOrderList(oerderCartId, fabricOrderId);
        for (CartEntity entity : farbicOrderList) {
            double lastDiscount = 1;
            // 购物车对应的面料基本信息
            MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(entity.getFabricId());
            // 获取购买数量
            double buyNumber = entity.getBuyNumber();

            if (fabricInfo != null) {
                if (fabricInfo.getFabricPrice() == null && fabricInfo.getGroupId() != null) {
                    // 重新寻早面料的价格(拿到了标准单价)
                    fabricInfo = fabricUtil.addPrice(fabricInfo, buyNumber);
                    System.out.println("面料的单价===" + fabricInfo.getFabricPrice());
                    // 获取面料折扣
                    lastDiscount = fabricUtil.userFabricDiscount(userDetail.getId() + "", fabricInfo.getGroupId());
                    fabricInfo.setKehuzk(lastDiscount);
                }
            }
            // 计算面料的价格
            double discountPrice = (fabricInfo.getFabricPrice().doubleValue() * buyNumber * lastDiscount);
            BigDecimal bigDecimal = new BigDecimal(discountPrice);
            double cleanPrice = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            entity.setTotalAmount(cleanPrice + "");

            entity.setStatus(orderinfo.getStatus());
        }
        return farbicOrderList;
    }

    /**
     * 面料订单售后
     *
     * @param token      令牌
     * @param orderSn    面料订单编号
     * @param number     物流单号
     * @param reason     售后原因
     * @param salaryType 售后类型 默认0退货，1换货，2返修，3重做
     */
    @Override
    public int fabricAfterSales(String token, String orderSn, String number, String reason, int salaryType) {
        if (!fabricUtil.checkToken(token)) return -1; // token校验
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccFabricOrderinfo orderinfo = mapper.selectOne(wrapper);
        orderinfo.setLogisticsSn(number).setStatus(6);
        int upduateResult = mapper.updateById(orderinfo);
        MlccAfterSalesinfo salesinfo = new MlccAfterSalesinfo();
        salesinfo.setUserId(userDetail.getId() + "").setOrderId(orderinfo.getId() + "").setReason(reason)
                .setAfterSalesType(salaryType).setCreateBy(userDetail.getUsername())
                .setUpdateBy(userDetail.getUsername()).setOrdertype(0);
        int insert = afterSalesinfoMapper.insert(salesinfo);
        if (upduateResult > 0 && insert > 0) {
            return 1;
        } else
            return 0;
    }

    /**
     * 获取用户订单列表
     *
     * @param pageNo
     * @param pageSize
     * @param token
     * @param orderType
     * @param startTime
     * @param endTime
     * @param status
     * @param code
     */
    @Override
    public JSONObject getAfterSalesList(Integer pageNo, Integer pageSize, String token, int orderType, Date startTime, Date endTime, Integer status, String code) {
        JSONObject result = new JSONObject();
        /*对token的校验*/
        if (!fabricUtil.checkToken(token)) {
            result.put("code", "1");
            result.put("msg", "token失效");
            return result;
        }
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        /*目前只做个订订单*/
        if (orderType == 1) {
            Page<MlccAfterSalesinfo> page = new Page<>(pageNo, pageSize);
            QueryWrapper<MlccAfterSalesinfo> wrapper = new QueryWrapper<>();
            wrapper.eq("ordertype", 1).eq("user_id", userDetail.getId());
            if (startTime != null)
                wrapper.ge("create_time", startTime);
            if (endTime != null)
                wrapper.le("create_time", endTime);
            if (code != null)
                wrapper.like("after_code", code);
            IPage<MlccAfterSalesinfo> selectPage = afterSalesinfoMapper.selectPage(page, wrapper);
            result.put("code", 0);
            result.put("msg", "查询成功");
            result.put("data", selectPage);
            return result;
        } else {
            return null;
        }
    }

    /**
     * 我的订单界面导出订单Excel 个订
     *
     * @param token 令牌
     */
    @Override
    public List<SingOrderExcel> getOrderExcel(String token) {
        if (!fabricUtil.checkToken(token)) return null;
        List<SingOrderExcel> orderExcel = excelMapper.getSingOrderExcel(token);
        if (orderExcel != null && orderExcel.size() > 0) {
            for (SingOrderExcel single : orderExcel) {
                QueryWrapper<MlccStoreInfo> storeWwrapper = new QueryWrapper<>();
                storeWwrapper.eq("store_code", single.getStoreId());
                MlccStoreInfo storeInfo = storeMapper.selectOne(storeWwrapper);
                if (storeInfo != null) {
                    single.setStoreName(storeInfo.getStoreName());
                }
                // 查询下单员工
                MlccUserInfo userInfo = userInfoMapper.selectById(single.getUserId());
                if (userInfo != null) {
                    single.setEmpName(userInfo.getRealname());
                }
            }
        }
        return orderExcel;
    }

    /**
     * 面料订单导出Excel
     *
     * @param token 令牌
     */
    @Override
    public List<MyFabricOrderExcel> getFabricOrderExcel(String token) {
        if (!fabricUtil.checkToken(token)) return null;
        List<MyFabricOrderExcel> orderExcel = excelMapper.getFabricOrderExcel(token);
        if (orderExcel != null && orderExcel.size() > 0) {
            for (MyFabricOrderExcel excel : orderExcel) {
                MlccStoreInfo storeInfo = storeMapper.selectById(excel.getStoreId());
                if (storeInfo != null) {
                    excel.setStoreName(storeInfo.getStoreName());
                }
                // 查询下单员工
                MlccUserInfo userInfo = userInfoMapper.selectById(excel.getUserId());
                if (userInfo != null) {
                    excel.setEmpName(userInfo.getRealname());
                }
            }
        }
        return orderExcel;
    }

    /**
     * 导出团订列表Excel
     *
     * @param token 令牌
     */
    @Override
    public List<TeamOrderExcel> getTeamOrderExcel(String token) {
        if (!fabricUtil.checkToken(token)) return null;
        List<TeamOrderExcel> orderExcel = excelMapper.getTeamOrderExcel(token);
        if (orderExcel != null && orderExcel.size() > 0) {
            for (TeamOrderExcel excel : orderExcel) {
                MlccStoreInfo storeInfo = storeMapper.selectById(excel.getStoreId());
                if (storeInfo != null) {
                    excel.setStoreName(storeInfo.getStoreName());
                }
                // 查询下单员工
                MlccUserInfo userInfo = userInfoMapper.selectById(excel.getUserId());
                if (userInfo != null) {
                    excel.setEmpName(userInfo.getRealname());
                }
            }
        }
        return orderExcel;
    }

    /**
     * 我的订单——个订售后
     *
     * @param token      令牌
     * @param orderSn    订单编号
     * @param salaryType 售后类型
     * @param reason     售后原因
     * @param number     运单号
     * @return 返回结果
     */
    @Override
    public int SingleOrderAfter(String token, String orderSn, int salaryType, String reason, String number) {
        if (!fabricUtil.checkToken(token)) return -1;// token验证都过不了  ԅ(¯﹃¯ԅ)
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSingleOrderInfo one = singleOrderInfoMapper.selectOne(wrapper);
        one.setUpdateBy(userDetail.getUsername()).setStatus(9);
        int updateById = singleOrderInfoMapper.updateById(one);// 更新原订单状态
        /*在售后表新增一条数据*/
        MlccAfterSalesinfo salesinfo = new MlccAfterSalesinfo();
        salesinfo.setUserId(userDetail.getId() + "").setOrderId(one.getId() + "").setReason(reason)
                .setAfterSalesType(salaryType).setCreateBy(userDetail.getUsername())
                .setUpdateBy(userDetail.getUsername()).setOrdertype(1);
        int insert = afterSalesinfoMapper.insert(salesinfo);
        if (updateById > 0 && insert > 0) {
            return 1; // 申请售后成功
        } else
            return 0; // 失败
    }

    /**
     * 我的订单——团订售后
     *
     * @param token      令牌
     * @param orderSn    订单编号
     * @param salaryType 售后类型
     * @param reason     售后原因
     * @param number     运单号
     * @return 返回结果
     */
    @Override
    public int teamOrderAfter(String token, String orderSn, int salaryType, String reason, String number) {
        if (!fabricUtil.checkToken(token)) return -1;// token验证都过不了  ԅ(¯﹃¯ԅ)
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccTeamOrderInfo one = teamOrderMapper.selectOne(wrapper);
        one.setUpdateBy(userDetail.getUsername()).setStatus(9);
        int updateById = teamOrderMapper.updateById(one);// 更新原订单状态
        /*在售后表新增一条数据*/
        MlccAfterSalesinfo salesinfo = new MlccAfterSalesinfo();
        salesinfo.setUserId(userDetail.getId() + "").setOrderId(one.getId() + "").setReason(reason)
                .setAfterSalesType(salaryType).setCreateBy(userDetail.getUsername())
                .setUpdateBy(userDetail.getUsername()).setOrdertype(2);
        int insert = afterSalesinfoMapper.insert(salesinfo);
        if (updateById > 0 && insert > 0) {
            return 1; // 申请售后成功
        } else
            return 0; // 失败
    }

    /**
     * 个订返修更新产品尺寸
     *
     * @param token     令牌
     * @param productID 产品ID
     * @param sizeID    尺寸ID
     * @param sizeValue 具体的值
     */
    @Override
    public int updateProductSize(String token, String productID, String sizeID, String sizeValue) {
        if (!fabricUtil.checkToken(token)) return -1;// token验证都过不了  ԅ(¯﹃¯ԅ)
        QueryWrapper<MlccProductBodysize> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productID).eq("bodysize_id", sizeID);
        MlccProductBodysize bodysize = productBodySizeMapper.selectOne(wrapper);
        bodysize.setBodysizeValue(sizeValue);
        return productBodySizeMapper.updateById(bodysize);
    }

    /**
     * 个订——返修界面提交
     *
     * @param afterCode 售后订单编号
     * @param token     令牌
     * @param orderSn   订单编号
     * @param reason    售后原因
     * @param imgURL    售后图片
     * @param money     售后金额
     */
    @Override
    public int updateSingleOrder(String afterCode, String token, String orderSn, String reason, String imgURL, String money, String pid) {
        if (!fabricUtil.checkToken(token)) return -1;// token验证都过不了  ԅ(¯﹃¯ԅ)
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        // 查询这条售后记录的基本信息
        QueryWrapper<MlccAfterSalesinfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("after_code", afterCode).eq("status", 1);
        MlccAfterSalesinfo mlccAfterSalesinfo = afterSalesinfoMapper.selectOne(wrapper1);
        // 售后订单支付
        int payResult = fabricUtil.payAfterOrder(new BigDecimal(Double.valueOf(money)), token, mlccAfterSalesinfo);
        if (payResult > 0) {

            // 事件表插入数据
            inserEvent(1, 1, "个订订单申请售后", orderSn, 2, mlccAfterSalesinfo.getId() + "", afterCode);

            // 啊啊啊！要启用返修的成本啊！！！（注意：这个功能在同意售后之后才开始）
            //orderService.takeonFanxiuChengben(orderSn, afterCode);
            /*更新原订单状态*/
            QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccSingleOrderInfo orderInfo = singleOrderInfoMapper.selectOne(wrapper);
            orderInfo.setStatus(9);
            int updateResult = singleOrderInfoMapper.updateById(orderInfo);

            // 查询门店信息
            QueryWrapper<MlccStoreInfo> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("store_code", orderInfo.getStoreId());
            MlccStoreInfo storeInfo = storeMapper.selectOne(wrapper2);

            /*向返修表插入数据*/
            MlccRepairOrderInfo repairOrderInfo = new MlccRepairOrderInfo();
            repairOrderInfo.setUserId(userDetail.getId() + "").setOrderId(orderInfo.getId() + "")
                    .setRepairReason(reason).setType(0).setCreateBy(userDetail.getUsername())
                    .setUpdateBy(userDetail.getUsername()).setImgurl(imgURL).setRepairMoney(money).setAfterCode(afterCode);
            int insertResult = reoairMapper.insert(repairOrderInfo);
            if (updateResult > 0 && insertResult > 0) {

                // 向异常订单添加一条数据
                MlccErrorOrder errorOrder = new MlccErrorOrder();
                errorOrder.setId(UUID.randomUUID().toString()).setErrorName("售后订单")
                        .setOrderSn(orderSn).setOrderType(1);
                errorOrderMapper.insert(errorOrder);

                // 向订单跟踪表插入数据
                MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
                trackingOrder.setId(UUID.randomUUID().toString().substring(0, 12)).setOrderSn(orderSn).setOrderStatus(2)
                        .setThing("申请售后")
                        .setOrderType(1).setRemark(reason).setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
                trackingOrderMapper.insert(trackingOrder);

                // 接下来向订单售后表更新记录（将这条售后订单表记录启用）
                if (mlccAfterSalesinfo != null) {
                    mlccAfterSalesinfo.setReason(reason).setRemark(reason).setImg(imgURL).setStatus(0)
                            .setSysOrgCode(userDetail.getOrgCode()).setAfterstatus(0).setAfterPrice(money).setProductId(pid);
                    afterSalesinfoMapper.updateById(mlccAfterSalesinfo);

                    // 接下来向订单流水表插入数据
                    MlccBusinessWaterInfo waterInfo = new MlccBusinessWaterInfo();
                    waterInfo.setId(UUID.randomUUID().toString()).setType(1).setUserId(userDetail.getId() + "")
                            .setCostMoney(money).setYewuInstructions("售后订单").setYewuDeatil("个订售后支付金额").setStatus(2)
                            .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername()).setOrderSn(orderSn)
                            .setStoreId(storeInfo.getId() + "")
                            .setApplyMethod(3).setAfterOrderSn(afterCode).setIsAfter(1).setSysOrgCode(userDetail.getOrgCode());
                    businessWaterInfoMapper.insert(waterInfo);
                }
                return 1;
            }
        }
        return 0;
    }

    /**
     * 团订返修界面的查询员工
     *
     * @param token      令牌
     * @param codeOrName 员工名称或者编码
     * @param customerId 订单里的客户ID
     */
    @Override
    public List<MlccCustomerInfo> selectEmployees(String token, String codeOrName, String customerId) {
        if (!fabricUtil.checkToken(token)) return null;
        return selectEmpMapper.selectEmployees(codeOrName, customerId);
    }

    /**
     * 团订返修界面获取团订基本信息
     *
     * @param token   令牌
     * @param orderSn 团订订单号
     */
    @Override
    public MlccTeamOrderInfo getTeamOrderDetail(String token, String orderSn) {
        if (!fabricUtil.checkToken(token)) return null;
        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        return teamOrderMapper.selectOne(wrapper);
    }

    /**
     * 团订返修界面获取部门下产品列表
     *
     * @param token
     * @param departid
     * @param orderSn
     */
    @Override
    public List<MlccProductInfo> getProductList(String token, String departid, String orderSn) {
        if (!fabricUtil.checkToken(token)) return null;
        // 拿到所有的部门产品关联数据
        QueryWrapper<MlccDepartProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_depart_id", departid);
        List<MlccDepartProduct> departProducts = departProductMapper.selectList(wrapper);

        ArrayList<MlccProductInfo> productInfos = new ArrayList<>(); // 存放部门下所有产品
        if (departProducts != null && departProducts.size() > 0) {
            for (MlccDepartProduct departProduct : departProducts) {
                QueryWrapper<MlccProductInfo> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("id", departProduct.getProductId()).eq("order_sn", orderSn);
                MlccProductInfo info = productInfoMapper.selectOne(wrapper1);
                if (info != null)
                    productInfos.add(info);
            }
        }
        return productInfos;
    }

    /**
     * 根据选中的产品获取尺寸列表
     *
     * @param token
     * @param productID
     */
    @Override
    public List<MlccProductBodysize> getSizeList(String token, String productID) {
        if (!fabricUtil.checkToken(token)) return null;
        MlccProductInfo productInfo = productInfoMapper.selectById(productID);
        if (productInfo != null && productInfo.getBodySizeIds() != null) {
            List<String> bodySizeIDs = Arrays.asList(productInfo.getBodySizeIds().split(","));
            QueryWrapper<MlccProductBodysize> wrapper = new QueryWrapper<>();
            wrapper.in("id", bodySizeIDs).eq("product_id", productID);
            List<MlccProductBodysize> bodysizes = productBodySizeMapper.selectList(wrapper);
            for (MlccProductBodysize bodysize : bodysizes) {
                String categoryId = bodySizeMapper.selectById(bodysize.getBodysizeId()).getCategoryId();
                bodysize.setTypeName(categoryInfoMapper.selectById(categoryId).getCategoryName());
                bodysize.setSizeName(bodySizeMapper.selectById(bodysize.getBodysizeId()).getBodySizename());
                bodysize.setUnit(bodySizeMapper.selectById(bodysize.getBodysizeId()).getUnit());
            }
            return bodysizes;
        }
        return null;
    }

    /**
     * 我的订单未支付订单的取消订单
     *
     * @param token     令牌
     * @param orderType 订单类型 3面料  0个订订单  1团订订单
     * @param orderSn   订单编号
     */
    @Override
    public int delOrder(String token, Integer orderType, String orderSn) {
        if (!fabricUtil.checkToken(token)) return -1;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        if (orderType == 3) { // 对面料订单的取消订单
            QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectOne(wrapper);
            orderinfo.setStatus(-1).setUpdateBy(userDetail.getUsername());
            int i = fabricOrderinfoMapper.updateById(orderinfo); // 更新的结果
            // 删除面料流水
            if (i > 0) {
                delWrater(orderSn);
            }

            // 向订单跟踪表插入数据
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setId(UUID.randomUUID().toString()).setOrderSn(orderSn).setOrderStatus(8).setThing("取消订单")
                    .setOrderType(0).setRemark("取消订单").setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
            trackingOrderMapper.insert(trackingOrder);
            return i;
        } else if (orderType == 0) { // 个订未支付删除
            QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccSingleOrderInfo info = singleOrderInfoMapper.selectOne(wrapper);
            info.setStatus(-1).setUpdateBy(userDetail.getUsername());
            int i = singleOrderInfoMapper.updateById(info);
            // 删除个订流水
            if (i > 0) {
                delWrater(orderSn);
            }
            return i;
        } else if (orderType == 1) { // 团订
            QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectOne(wrapper);
            teamOrderInfo.setStatus(-1).setUpdateBy(userDetail.getUsername());
            int i = teamOrderMapper.updateById(teamOrderInfo);
            // 删除团订流水
            if (i > 0) {
                delWrater(orderSn);
            }
            return i;
        } else if (orderType == 2) {
            // 现货订单取消
            QueryWrapper<MlccThirdGoodsOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", orderSn);
            MlccThirdGoodsOrder goodsOrder = goodsOrderMapper.selectOne(wrapper);
            goodsOrder.setStatus(-1);
            int i = goodsOrderMapper.updateById(goodsOrder);
            // 删除现货订单流水
            if (i > 0) {
                delWrater(orderSn);
            }
            return i;
        }
        return -2;
    }

    /**
     * 订单跟踪状态
     *
     * @param token
     * @param orderSn
     */
    @Override
    public List<MlccTrackingOrder> getFabricOrderTracking(String token, String orderSn, Integer orderType) {
        if (!fabricUtil.checkToken(token)) return null;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        QueryWrapper<MlccTrackingOrder> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        if (orderType == 3) { // 查询面料订单状态
            wrapper.eq("order_sn", orderSn);
            return trackingOrderMapper.selectList(wrapper);
        } else if (orderType == 0) { //个订订单状态跟踪
            wrapper.eq("order_sn", orderSn);
            return trackingOrderMapper.selectList(wrapper);
        } else if (orderType == 1) { // 团订
            wrapper.eq("order_sn", orderSn);
            return trackingOrderMapper.selectList(wrapper);
        }
        return null;
    }

    /**
     * 我的订单，订单详情的立即支付
     *
     * @param token     令牌
     * @param orderType 订单类型 3面料订单，0个订，1团订
     * @param orderSn   订单编号
     * @return 支付的结果
     */
    @Override
    @Transactional
    public int buyNow(String token, Integer orderType, String orderSn, String remark) {
        if (!fabricUtil.checkToken(token)) return -1; // token校验不通过
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        /*用于订单跟踪表的插入对象*/
        MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
        if (orderType == 3) {
            /*面料订单立即支付*/
            return fabricOrderBuy(userDetail, trackingOrder, orderSn, remark);
        } else if (orderType == 0) {
            /*个订订单支付*/
            return singleOrderBuy(userDetail, trackingOrder, orderSn, remark);
        } else if (orderType == 1) {
            /*团订支付*/
            return teamOrderBuy(userDetail, trackingOrder, orderSn, remark);
        } else {
            /*没有这种订单类型*/
            return 0;
        }
    }

    /**
     * web端我的订单——面料订单申请售后
     *
     * @param token     令牌
     * @param orderSn   订单号
     * @param remark    申请售后原因
     * @param afterType 售后类型 0退货，1换货
     * @param cart      （购物车id）
     * @return 结果
     */
    @Override
    public int applicationAafter(String token, String orderSn, String remark, Integer afterType, String img, String cart) {
        if (!fabricUtil.checkToken(token)) return -1; // token校验
        // 如果这个产品已经退款（直接返回）
        MlccCartInfo cartInfo1 = cartInfoMapper.selectById(cart);
        if (cartInfo1 != null && cartInfo1.getIsTui() == 1) {
            return -7;
        }

        // 如果这个产品已经提交售后，后台还没有处理，不能继续提交售后
        QueryWrapper<MlccAfterSalesinfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("order_sn", orderSn).eq("ordertype", 0).eq("cart_id", cart)
                .in("afterstatus", 0, 1, 2);
        int ooo = afterSalesinfoMapper.selectCount(wrapper1);
        if (ooo > 0) {
            return -6;
        }

        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        // 订单基本信息
        QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectOne(wrapper);
        // 修改订单状态（申请售后）
        orderinfo.setStatus(6).setUpdateBy(userDetail.getUsername());
        int updateOrderResult = fabricOrderinfoMapper.updateById(orderinfo);// 更新订单表

        if (updateOrderResult > 0) {
            // 往订单跟踪表插入数据
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setOrderSn(orderSn).setOrderType(0).setRemark(remark).setOrderStatus(2)
                    .setThing("申请售后")
                    .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
            trackingOrderMapper.insert(trackingOrder);

            // 向异常订单添加一条数据
            MlccErrorOrder errorOrder = new MlccErrorOrder();
            errorOrder.setId(UUID.randomUUID().toString()).setErrorName("售后订单")
                    .setOrderSn(orderSn).setOrderType(0);
            errorOrderMapper.insert(errorOrder);
            // 往订单售后表添加数据
            MlccAfterSalesinfo salesinfo = new MlccAfterSalesinfo();
            // 查询购物车基本信息
            MlccCartInfo cartInfo = cartInfoMapper.selectById(cart);
            // 获取购物车下的面料
            MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(cartInfo.getFabricId());
            // 创建一个随机数
            Random random = new Random();
            int i = random.nextInt(9999);
            salesinfo.setUserId(userDetail.getId() + "").setOrderId(orderinfo.getId() + "").setReason(remark).setAfterstatus(0)
                    .setAfterSalesType(afterType).setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername())
                    .setFabricids(fabricInfo.getFabricCode()).setCartId(cart).setSysOrgCode(userDetail.getOrgCode())
                    .setOrdertype(0).setAfterCode(System.currentTimeMillis() + "" + i).setOrderSn(orderSn).setImg(img);
            if (afterType == 0) {
                // 如果是退货，售后金额就是购物车的金额
                salesinfo.setAfterPrice(cartInfo.getTotalAmount());
            }
            afterSalesinfoMapper.insert(salesinfo);
            // 事件表插入数据
            inserEvent(0, 1, "面料订单申请售后", orderSn, 2, salesinfo.getId() + "", salesinfo.getAfterCode());
        }
        return updateOrderResult;
    }

    /**
     * 个订取产品状态跟踪列表
     *
     * @param token   令牌
     * @param orderSn 订单编号
     */
    @Override
    public List<MlccTrackingProduct> listtrackingProduct(String token, String orderSn) {
        if (!fabricUtil.checkToken(token)) return null; // token校验
        // 个订查询产品状态跟踪
        QueryWrapper<MlccTrackingProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).ne("status", "4").orderByDesc("create_time");
        List<MlccTrackingProduct> trackingProducts = trackingProductMapper.selectList(wrapper);
        if (trackingProducts != null && trackingProducts.size() > 0) {
            for (MlccTrackingProduct track : trackingProducts) {
                MlccProductInfo productInfo = productInfoMapper.selectById(track.getProductId());
                if (productInfo != null) {
                    track.setProductName(productInfo.getProductName());
                }
            }
        }
        return trackingProducts;
    }

    /**
     * 根据产品ID获取可以返修的身体数据
     *
     * @param token     令牌
     * @param priductID 产品ID
     */
    @Override
    public Set<MlccCategoryFanxiuInfo> listProductBodySize(String token, String priductID) {
        if (!fabricUtil.checkToken(token)) return null; // token校验
        /*1、首先拿到产品的类别ID，根据类别ID来区分那些尺寸参数支持返修*/
        MlccProductInfo productInfo = productInfoMapper.selectById(priductID);
        if (productInfo == null || productInfo.getCategoryIds() == null) {
            return null;
        }
        String PLID = fabricUtil.getpingleiFromProduct(productInfo);
        HashSet<MlccCategoryFanxiuInfo> set = new HashSet<>();
        if (PLID != null) {
            QueryWrapper<MlccCategoryFanxiuInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("category_id", PLID);
            List<MlccCategoryFanxiuInfo> fanxiuInfos = fanxiuMapper.selectList(wrapper);
            if (fanxiuInfos != null && fanxiuInfos.size() > 0) {
                fanxiuInfos.stream().forEach(fanxiu -> {
                    set.add(fanxiu);
                });
            }
        }
        /*String[] split = productInfo.getCategoryIds().split(",");
        List<String> categoryIDList = Arrays.asList(split);
        HashSet<MlccCategoryFanxiuInfo> set = new HashSet<>();
        for (String cateid : categoryIDList) {
            QueryWrapper<MlccCategoryFanxiuInfo> wrapper = new QueryWrapper<>();
            wrapper.like("category_id", cateid);
            List<MlccCategoryFanxiuInfo> infoList = fanxiuMapper.selectList(wrapper);
            for (MlccCategoryFanxiuInfo info : infoList) {
                set.add(info);
            }
        }*/
        return set;
    }

    /**
     * 个订产品返修
     *
     * @param token     令牌
     * @param productID 产品ID
     * @param sizeID    尺寸ID
     * @param sizeValue 尺寸值
     */
    @Override
    public int saveFanxiuSize(String afterCode, String token, String productID, String sizeID, String sizeValue, String sizeTitle, String orderSn) {
        if (!fabricUtil.checkToken(token)) return -1; // token校验
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        QueryWrapper<MlccSingleOrderInfo> singleOrderInfoQueryWrapper = new QueryWrapper<>();
        singleOrderInfoQueryWrapper.eq("order_sn", orderSn);
        // 查询个订订单的基本信息
        MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectOne(singleOrderInfoQueryWrapper);
        // 查询产品尺寸表
        QueryWrapper<MlccProductBodysize> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productID).eq("bodysize_id", sizeID).eq("isfanxiu", 1)
                .eq("after_code", afterCode).eq("order_sn", orderSn);
        MlccProductBodysize bodysize = productBodySizeMapper.selectOne(wrapper);
        int result = 0;
        if (bodysize != null) {
            // 更新之前的返修记录操作
            bodysize.setBodysizeValue(sizeValue).setUpdateBy(userDetail.getUsername());
            result = productBodySizeMapper.updateById(bodysize);
            System.out.println("制定了更新操作，ID是：" + bodysize.getId());
        } else {
            // 添加新的返修尺寸记录
            MlccProductBodysize bodysize1 = new MlccProductBodysize();
            bodysize1.setProductId(productID).setBodysizeId(sizeID).setBodysizeValue(sizeValue).setCreateBy(userDetail.getUsername())
                    .setUpdateBy(userDetail.getUsername()).setIsfanxiu(1).setOrderSn(orderSn).setAfterCode(afterCode);
            result = productBodySizeMapper.insert(bodysize1);
            System.out.println("制定了插入操作，ID是：" + bodysize1.getId());
        }
        if (result > 0) {

            // 向派单成本表添加返修记录
            orderService.saveFanxiuChengben(afterCode, productID, sizeID, orderSn, sizeTitle, null);

            // 更新完毕之后，向产品状态跟踪表添加数据
            MlccTrackingProduct product = new MlccTrackingProduct();
            product.setProductId(productID).setStatus(4).setRemark("返修，修改" + sizeTitle + ",改为" + sizeValue).setCreateBy(userDetail.getUsername())
                    .setUpdateBy(userDetail.getUsername());
            trackingProductMapper.insert(product);
        }
        return result;
    }

    /**
     * 订单售后记录跟踪
     *
     * @param token     令牌
     * @param orderSn   订单编号
     * @param orderType 订单类型
     * @return 售后记录列表
     */
    @Override
    public IPage<MlccAfterSalesinfo> listTeamAfter(Page<MlccAfterSalesinfo> page, String token, String orderSn, Integer orderType) {
        if (!fabricUtil.checkToken(token)) return null;

        QueryWrapper<MlccAfterSalesinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("status", 0);
        if (orderType == 3) { // 如果是面料订单
            wrapper.eq("ordertype", 0);
        } else if (orderType == 0) { // 如果是个订
            wrapper.eq("ordertype", 1);
        } else if (orderType == 1) { // 如果是团订
            wrapper.eq("ordertype", 2);
            /*return orderAafterTMapper.listTeamAfter(page, orderSn);*/
        }
        wrapper.orderByDesc("create_time");
        IPage<MlccAfterSalesinfo> iPage = afterSalesinfoMapper.selectPage(page, wrapper);
        List<MlccAfterSalesinfo> records = iPage.getRecords();
        if (records != null && records.size() > 0) {
            for (MlccAfterSalesinfo record : records) {
                MlccUserInfo userInfo = userInfoMapper.selectById(record.getUserId());
                if (userInfo != null) {
                    // 查询到了售后下单的员工
                    record.setStoreName(userInfo.getRealname());
                }
            }
        }
        return iPage;
    }

    /**
     * 创建一条个订售后订单
     *
     * @param orderSn 个订订单编号
     */
    @Override
    public String createSingleAfterOrder(String orderSn, String token) {
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectOne(wrapper);
        // 创建一个随机数
        Random random = new Random();
        int i = random.nextInt(9999);
        // 插入数据
        MlccAfterSalesinfo afterSalesinfo = new MlccAfterSalesinfo();
        afterSalesinfo.setAfterCode(System.currentTimeMillis() + "" + i).setUserId(singleOrderInfo.getUserId()).setOrderId(singleOrderInfo.getId() + "")
                .setAfterSalesType(2).setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername()).setOrdertype(1)
                .setOrderSn(orderSn).setStatus(1);
        int insert = afterSalesinfoMapper.insert(afterSalesinfo);
        if (insert > 0) {
            return afterSalesinfo.getAfterCode();
        }
        return null;
    }

    /**
     * 查询个订订单本次返修的价格
     *
     * @param afterCode 售后订单编号
     * @param orderSn   个订顶订单编号
     * @param pid       产品id
     */
    @Override
    public double selectSingleFanxiuPrice(String afterCode, String orderSn, String pid) {
        BigDecimal price = new BigDecimal(0);
        // 查询本次返修的返修参数集合
        QueryWrapper<MlccProductBodysize> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("isfanxiu", 1).eq("after_code", afterCode).eq("product_id", pid);
        List<MlccProductBodysize> productBodysizes = productBodySizeMapper.selectList(wrapper);
        // 遍历集合
        if (productBodysizes != null && productBodysizes.size() > 0) {
            for (MlccProductBodysize bodysize : productBodysizes) {
                String productId = bodysize.getProductId();
                MlccProductInfo productInfo = productInfoMapper.selectById(productId);
                // 获取产品的品类ID
                String PLID = fabricUtil.getpingleiFromProduct(productInfo);
                if (PLID != null) {
                    // 确定业务类型
                    QueryWrapper<MlccPriceSystemPinglei> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("category_id", PLID).eq("business_type", 0);
                    MlccPriceSystemPinglei systemPinglei = priceSystemPingleiMapper.selectOne(wrapper1);
                    if (systemPinglei != null) {
                        QueryWrapper<MlccPriceSystemCostRecord> recordQueryWrapper = new QueryWrapper<>();
                        recordQueryWrapper.eq("cost_item", PLID).eq("cost_id", bodysize.getBodysizeId()).eq("type", 6)
                                .eq("price_system_id", systemPinglei.getId());
                        MlccPriceSystemCostRecord record = recordMapper.selectOne(recordQueryWrapper);
                        if (record != null) {
                            price = price.add(record.getPrice());
                        }
                    }
                }
            }
        }
        return price.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }


    /*-------------------------下面三个方法用于我的订单界面订单的支付------------------------------*/

    /**
     * 我的订单——未支付面料订单的支付
     *
     * @param userDetail
     * @param trackingOrder
     * @param orderSn
     * @param remark
     */
    public int fabricOrderBuy(MlccUserInfo userDetail, MlccTrackingOrder trackingOrder, String orderSn, String remark) {
        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> cwrapper = new QueryWrapper<>();
        cwrapper.eq("company_code", userDetail.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(cwrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            userDetail = companyUser;
        }
        // 查询面料订单基本信息
        QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("status", 0);
        MlccFabricOrderinfo orderinfo = fabricOrderinfoMapper.selectOne(wrapper);
        if (orderinfo == null) return -3;// 这个订单已经支付过了
        // 三个额度加起来的金额都不够？提示余额不足
        BigDecimal money = new BigDecimal(Double.valueOf(orderinfo.getOrderMoney())); // 订单金额
        BigDecimal userbalance = new BigDecimal(Double.valueOf(userDetail.getAccountBalance())); // 用户余额金额

        // 判断用户的总余额是否充足？ 0足够，1余额不足
        int check = fabricUtil.cheakMoney(userDetail, money);
        if (check == 1) {
            return -2;
        }
         /*进行支付
         查询抵扣额度，是否需要从抵扣额度进行扣款？
         如果抵扣额度足够支付订单金额*/
        if (userDetail.getDeductionLimit().doubleValue() >= money.doubleValue()) {
            // 更新抵扣额度
            userDetail.setDeductionLimit(userDetail.getDeductionLimit().subtract(money));
            // 面料订单只有抵扣额度支付
            orderinfo.setApplyType(3).setDeductionPay(money);
        } else {
            // 抵扣额度不够支付订单，加上月结剩余额度是否足够支付？
            // 如果抵扣额度加上月结剩余额度足够支付订单，进行支付
            if (userDetail.getDeductionLimit().add(userDetail.getRemainingLimit()).doubleValue() >= money.doubleValue()) {
                BigDecimal subtract = new BigDecimal(money.doubleValue());
                // 抵扣额度是否是负数？？？
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    // 扣除抵扣额度的价格
                    subtract = money.subtract(userDetail.getDeductionLimit());
                }

                // 更新订单基本信息
                orderinfo.setMonthPay(subtract).setApplyType(3);
                // 更新账号的抵扣额度和月结剩余额度，抵扣额度清零
                userDetail.setRemainingLimit(userDetail.getRemainingLimit().subtract(subtract));
                // 大于0才清空，否则不清空
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    orderinfo.setDeductionPay(userDetail.getDeductionLimit());
                    userDetail.setDeductionLimit(new BigDecimal(0));
                }
            } else {
                // 三个额度加起来菜足够支付
                // 订单剩下的钱
                BigDecimal subtract = new BigDecimal(money.doubleValue());
                // 如果抵扣额度不是负数
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    // 扣除抵扣额度的价格
                    subtract = money.subtract(userDetail.getDeductionLimit());
                }
                // 如果月结额度不是负数
                if (userDetail.getRemainingLimit().doubleValue() > 0) {
                    // 扣除月结额度的价格
                    subtract = money.subtract(userDetail.getRemainingLimit());
                }

                // 更新订单基本信息
                orderinfo.setBalancePay(subtract).setApplyType(3);
                // 更新账号的抵扣额度和月结剩余额度和账户余额，抵扣额度清零，月结额度清零！！
                userDetail.setAccountBalance(userbalance.subtract(subtract).setScale(2, BigDecimal.ROUND_FLOOR).toString());
                // 大于0才清空，否则不清空
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    orderinfo.setDeductionPay(userDetail.getDeductionLimit());
                    userDetail.setDeductionLimit(new BigDecimal(0));
                }
                if (userDetail.getRemainingLimit().doubleValue() > 0) {
                    orderinfo.setMonthPay(userDetail.getRemainingLimit());
                    userDetail.setRemainingLimit(new BigDecimal(0));
                }
            }
        }
        // 更新用户的余额或月结额度
        int updateUser = userInfoMapper.updateById(userDetail);
        // 更新面料订单数据
        orderinfo.setStatus(1).setUpdateBy(userDetail.getUsername()).setRemark(remark);
        int updateOrder = fabricOrderinfoMapper.updateById(orderinfo);
        if (updateUser > 0 && updateOrder > 0) {
            // 向月结流水表添加数据
            if (orderinfo.getMonthPay() != null) {
                fabricUtil.savepay(userDetail.getId() + "", orderinfo.getMonthPay(), orderSn, 0, 0);
            }

            // 2、向业务流水表添加数据，这里要进行判断，确保一条订单只有一条流水数据
            QueryWrapper<MlccBusinessWaterInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_id", orderinfo.getId()).eq("type", 0);
            MlccBusinessWaterInfo businessWaterInfo = businessWaterInfoMapper.selectOne(wrapper1);
            if (businessWaterInfo == null) {
                MlccBusinessWaterInfo waterInfo = new MlccBusinessWaterInfo();
                waterInfo.setOrderId(orderinfo.getId() + "").setType(0).setUserId(userDetail.getId() + "")
                        .setOrderSn(orderSn).setStatus(2).setStoreId(orderinfo.getStoreId()).setSysOrgCode(userDetail.getOrgCode())
                        .setCostMoney(orderinfo.getOrderMoney()).setYewuInstructions("正常业务").setYewuDeatil("面料订单支付")
                        .setRemark(remark).setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
                businessWaterInfoMapper.insert(waterInfo);
            } else {
                businessWaterInfo.setStatus(2).setUpdateBy(userDetail.getUsername()).setSysOrgCode(userDetail.getOrgCode());
                businessWaterInfoMapper.updateById(businessWaterInfo);
            }

            // 更新流水
            updatewrater(orderinfo.getId() + "", 0);
            // 3、往订单跟踪表添加数据
            // 判断支付类型
            BigDecimal bijiao = new BigDecimal(0);
            if (orderinfo.getDeductionPay().compareTo(bijiao) == 0 && orderinfo.getMonthPay().compareTo(bijiao) == 0) {
                trackingOrder.setRemark("余额支付");
            } else if (orderinfo.getDeductionPay().compareTo(bijiao) == 0 && orderinfo.getBalancePay().compareTo(bijiao) == 0) {
                trackingOrder.setRemark("月结剩余额度支付");
            } else if (orderinfo.getBalancePay().compareTo(bijiao) == 0 && orderinfo.getMonthPay().compareTo(bijiao) == 0) {
                trackingOrder.setRemark("抵扣额度支付");
            } else {
                trackingOrder.setRemark("组合支付");
            }
            trackingOrder.setOrderSn(orderSn).setOrderType(0).setOrderStatus(1)
                    .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername()).setThing("订单支付");
            trackingOrderMapper.insert(trackingOrder);
            inserEvent(0, 0, "面料订单支付", orderSn, 1, null, null);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 我的订单——未支付个订订单的支付
     *
     * @param userDetail    用户信息
     * @param trackingOrder 订单跟踪信息
     * @param orderSn       订单编号
     * @param remark        备注
     */
    public int singleOrderBuy(MlccUserInfo userDetail, MlccTrackingOrder trackingOrder, String orderSn, String remark) {
        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> cwrapper = new QueryWrapper<>();
        cwrapper.eq("company_code", userDetail.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(cwrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            userDetail = companyUser;
        }

        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("status", 11);
        MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectOne(wrapper);
        if (singleOrderInfo == null) return -3;// 这个订单已经支付过了

        // 三个额度加起来的金额都不够？提示余额不足
        BigDecimal money = new BigDecimal(Double.valueOf(singleOrderInfo.getOrderMoney())); // 订单金额
        BigDecimal userbalance = new BigDecimal(Double.valueOf(userDetail.getAccountBalance())); // 用户余额金额

        // 判断用户的总余额是否充足？ 0足够，1余额不足
        int check = fabricUtil.cheakMoney(userDetail, money);
        if (check == 1) {
            return -2;
        }

        /*进行支付
         查询抵扣额度，是否需要从抵扣额度进行扣款？
         如果抵扣额度足够支付订单金额*/
        if (userDetail.getDeductionLimit().doubleValue() >= money.doubleValue()) {
            // 更新抵扣额度
            userDetail.setDeductionLimit(userDetail.getDeductionLimit().subtract(money));
            // 面料订单只有抵扣额度支付
            singleOrderInfo.setDeductionPay(money).setApplyType(3);
        } else {
            // 抵扣额度不够支付订单，加上月结剩余额度是否足够支付？
            // 如果抵扣额度加上月结剩余额度足够支付订单，进行支付
            if (userDetail.getDeductionLimit().add(userDetail.getRemainingLimit()).doubleValue() >= money.doubleValue()) {
                BigDecimal subtract = new BigDecimal(money.doubleValue());
                // 抵扣额度是否是负数？？？
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    // 扣除抵扣额度的价格
                    subtract = money.subtract(userDetail.getDeductionLimit());
                } else {
                    // 否则订单剩余的钱就没变
                    subtract = new BigDecimal(money.doubleValue());
                }
                // 更新订单基本信息
                singleOrderInfo.setMonthPay(subtract).setApplyType(3);
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    singleOrderInfo.setDeductionPay(userDetail.getDeductionLimit());
                }
                // 更新账号的抵扣额度和月结剩余额度，抵扣额度清零
                userDetail.setRemainingLimit(userDetail.getRemainingLimit().subtract(subtract));
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    userDetail.setDeductionLimit(new BigDecimal(0));
                }
            } else {

                // 订单剩下的钱
                BigDecimal subtract = new BigDecimal(money.doubleValue());
                // 如果抵扣额度不是负数
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    // 扣除抵扣额度的价格
                    subtract = money.subtract(userDetail.getDeductionLimit());
                }
                // 如果月结额度不是负数
                if (userDetail.getRemainingLimit().doubleValue() > 0) {
                    // 扣除月结额度的价格
                    subtract = money.subtract(userDetail.getRemainingLimit());
                }

                // 更新订单基本信息
                singleOrderInfo.setBalancePay(subtract).setApplyType(3);
                // 更新账号的抵扣额度和月结剩余额度和账户余额，抵扣额度清零，月结额度清零！！
                userDetail.setAccountBalance(userbalance.subtract(subtract).setScale(2, BigDecimal.ROUND_FLOOR).toString());

                // 大于0才清空，否则不清空
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    singleOrderInfo.setDeductionPay(userDetail.getDeductionLimit());
                    userDetail.setDeductionLimit(new BigDecimal(0));
                }
                if (userDetail.getRemainingLimit().doubleValue() > 0) {
                    singleOrderInfo.setMonthPay(userDetail.getRemainingLimit());
                    userDetail.setRemainingLimit(new BigDecimal(0));
                }
            }
        }
        // 更新用户的余额或月结额度
        int updateUser = userInfoMapper.updateById(userDetail);

        singleOrderInfo.setStatus(1).setUpdateBy(userDetail.getUsername()).setRemark(remark);
        int updateOrder = singleOrderInfoMapper.updateById(singleOrderInfo);
        if (updateUser > 0 && updateOrder > 0) { // 说明订单支付成功
            // 向月结流水表添加数据
            if (singleOrderInfo.getMonthPay() != null) {
                fabricUtil.savepay(userDetail.getId() + "", singleOrderInfo.getMonthPay(), orderSn, 1, 0);
            }
            // 2、向业务流水表添加数据，这里要进行判断，确保一条订单只有一条流水数据
            QueryWrapper<MlccBusinessWaterInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_id", singleOrderInfo.getId()).eq("type", 1);
            MlccBusinessWaterInfo businessWaterInfo = businessWaterInfoMapper.selectOne(wrapper1);
            // 查询门店信息，个订插入的竟然是门店编号？
            QueryWrapper<MlccStoreInfo> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("store_code", singleOrderInfo.getStoreId());
            MlccStoreInfo storeInfo = storeMapper.selectOne(wrapper2);

            if (businessWaterInfo == null) {
                MlccBusinessWaterInfo waterInfo = new MlccBusinessWaterInfo();
                waterInfo.setOrderId(singleOrderInfo.getId() + "").setType(1).setUserId(userDetail.getId() + "")
                        .setStoreId(storeInfo.getId() + "").setOrderSn(orderSn)
                        .setStatus(2).setSysOrgCode(userDetail.getOrgCode())
                        .setCostMoney(singleOrderInfo.getOrderMoney()).setYewuInstructions("正常业务").setYewuDeatil("个订订单支付")
                        .setRemark(remark).setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername()).setStatus(2);
                businessWaterInfoMapper.insert(waterInfo);
            } else {
                businessWaterInfo.setStatus(2).setUpdateBy(userDetail.getUsername()).setStoreId(storeInfo.getId() + "").setSysOrgCode(userDetail.getOrgCode());
                businessWaterInfoMapper.updateById(businessWaterInfo);
            }
            // 3、往订单跟踪表添加数据
            // 更新流水
            updatewrater(singleOrderInfo.getId() + "", 1);
            // 判断支付类型
            BigDecimal bijiao = new BigDecimal(0);
            if (singleOrderInfo.getDeductionPay().compareTo(bijiao) == 0 && singleOrderInfo.getMonthPay().compareTo(bijiao) == 0) {
                trackingOrder.setRemark("余额支付");
            } else if (singleOrderInfo.getDeductionPay().compareTo(bijiao) == 0 && singleOrderInfo.getBalancePay().compareTo(bijiao) == 0) {
                trackingOrder.setRemark("月结剩余额度支付");
            } else if (singleOrderInfo.getBalancePay().compareTo(bijiao) == 0 && singleOrderInfo.getMonthPay().compareTo(bijiao) == 0) {
                trackingOrder.setRemark("抵扣额度支付");
            } else {
                trackingOrder.setRemark("组合支付");
            }
            // 订单状态跟踪添加数据
            trackingOrder.setOrderSn(orderSn).setOrderType(1).setOrderStatus(1).setThing("订单支付")
                    .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
            trackingOrderMapper.insert(trackingOrder);
            // 事件表添加数据
            inserEvent(1, 0, "个订订单支付", orderSn, 1, null, null);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 我的订单——团订订单支付
     *
     * @param userDetail    门店对象
     * @param trackingOrder 订单状态跟踪表对象
     * @param orderSn       订单编号
     * @param remark        备注
     */
    public int teamOrderBuy(MlccUserInfo userDetail, MlccTrackingOrder trackingOrder, String orderSn, String remark) {
        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> cwrapper = new QueryWrapper<>();
        cwrapper.eq("company_code", userDetail.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(cwrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        } else {
            userDetail = companyUser;
        }

        QueryWrapper<MlccTeamOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("status", 11);
        MlccTeamOrderInfo teamOrderInfo = teamOrderMapper.selectOne(wrapper);
        if (teamOrderInfo == null) return -3;

        // 三个额度加起来的金额都不够？提示余额不足
        BigDecimal money = new BigDecimal(Double.valueOf(teamOrderInfo.getOrderMoney())); // 订单金额
        BigDecimal userbalance = new BigDecimal(Double.valueOf(userDetail.getAccountBalance())); // 用户余额金额

        // 判断用户的总余额是否充足？ 0足够，1余额不足
        int check = fabricUtil.cheakMoney(userDetail, money);
        if (check == 1) {
            return -2;
        }

        /*进行支付
         查询抵扣额度，是否需要从抵扣额度进行扣款？
         如果抵扣额度足够支付订单金额*/
        if (userDetail.getDeductionLimit().doubleValue() >= money.doubleValue()) {
            // 更新抵扣额度
            userDetail.setDeductionLimit(userDetail.getDeductionLimit().subtract(money));
            // 面料订单只有抵扣额度支付
            teamOrderInfo.setDeductionPay(money).setApplyType(3);
        } else {
            // 抵扣额度不够支付订单，加上月结剩余额度是否足够支付？
            // 如果抵扣额度加上月结剩余额度足够支付订单，进行支付
            if (userDetail.getDeductionLimit().add(userDetail.getRemainingLimit()).doubleValue() >= money.doubleValue()) {
                BigDecimal subtract = new BigDecimal(money.doubleValue());

                // 抵扣额度是否是负数？？？
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    // 扣除抵扣额度的价格
                    subtract = money.subtract(userDetail.getDeductionLimit());
                } else {
                    // 否则订单剩余的钱就没变
                    subtract = new BigDecimal(money.doubleValue());
                }

                // 更新订单基本信息
                teamOrderInfo.setMonthPay(subtract);
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    teamOrderInfo.setDeductionPay(userDetail.getDeductionLimit()).setApplyType(3);
                }
                // 更新账号的抵扣额度和月结剩余额度，抵扣额度清零
                userDetail.setRemainingLimit(userDetail.getRemainingLimit().subtract(subtract));
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    userDetail.setDeductionLimit(new BigDecimal(0));
                }
            } else {

                // 订单剩下的钱
                BigDecimal subtract = new BigDecimal(money.doubleValue());
                // 如果抵扣额度不是负数
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    // 扣除抵扣额度的价格
                    subtract = money.subtract(userDetail.getDeductionLimit());
                }
                // 如果月结额度不是负数
                if (userDetail.getRemainingLimit().doubleValue() > 0) {
                    // 扣除月结额度的价格
                    subtract = money.subtract(userDetail.getRemainingLimit());
                }

                // 更新订单基本信息
                teamOrderInfo.setBalancePay(subtract).setApplyType(3);
                // 更新账号的抵扣额度和月结剩余额度和账户余额，抵扣额度清零，月结额度清零！！
                userDetail.setAccountBalance(userbalance.subtract(subtract).setScale(2, BigDecimal.ROUND_FLOOR).toString());

                // 大于0才清空，否则不清空
                if (userDetail.getDeductionLimit().doubleValue() > 0) {
                    teamOrderInfo.setDeductionPay(userDetail.getDeductionLimit());
                    userDetail.setDeductionLimit(new BigDecimal(0));
                }
                if (userDetail.getRemainingLimit().doubleValue() > 0) {
                    teamOrderInfo.setMonthPay(userDetail.getRemainingLimit());
                    userDetail.setRemainingLimit(new BigDecimal(0));
                }
            }
        }
        // 更新用户的余额或月结额度
        int updateUser = userInfoMapper.updateById(userDetail);

        teamOrderInfo.setStatus(1).setUpdateBy(userDetail.getUsername()).setRemark(remark);
        int updateOrder = teamOrderMapper.updateById(teamOrderInfo);
        if (updateUser > 0 && updateOrder > 0) { // 说明订单支付成功
            // 向月结流水表添加数据
            if (teamOrderInfo.getMonthPay() != null) {
                fabricUtil.savepay(userDetail.getId() + "", teamOrderInfo.getMonthPay(), orderSn, 2, 0);
            }
            // 2、向业务流水表添加数据，这里要进行判断，确保一条订单只有一条流水数据
            QueryWrapper<MlccBusinessWaterInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_id", teamOrderInfo.getId()).eq("type", 2);
            MlccBusinessWaterInfo businessWaterInfo = businessWaterInfoMapper.selectOne(wrapper1);
            if (businessWaterInfo == null) {
                MlccBusinessWaterInfo waterInfo = new MlccBusinessWaterInfo();
                waterInfo.setOrderId(teamOrderInfo.getId() + "").setType(2).setUserId(userDetail.getId() + "")
                        .setStoreId(teamOrderInfo.getStoreId()).setOrderSn(orderSn)
                        .setStatus(2).setSysOrgCode(userDetail.getOrgCode())
                        .setCostMoney(teamOrderInfo.getOrderMoney()).setYewuInstructions("正常业务").setYewuDeatil("团订订单支付")
                        .setRemark(remark).setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername()).setStatus(2);
                businessWaterInfoMapper.insert(waterInfo);
            } else {
                businessWaterInfo.setStatus(2).setUpdateBy(userDetail.getUsername()).setSysOrgCode(userDetail.getOrgCode());
                businessWaterInfoMapper.updateById(businessWaterInfo);
            }
            // 3、往订单跟踪表添加数据
            // 更新流水
            updatewrater(teamOrderInfo.getId() + "", 2);
            // 判断支付类型
            BigDecimal bijiao = new BigDecimal(0);
            if (teamOrderInfo.getDeductionPay().compareTo(bijiao) == 0 && teamOrderInfo.getMonthPay().compareTo(bijiao) == 0) {
                trackingOrder.setRemark("余额支付");
            } else if (teamOrderInfo.getDeductionPay().compareTo(bijiao) == 0 && teamOrderInfo.getBalancePay().compareTo(bijiao) == 0) {
                trackingOrder.setRemark("月结剩余额度支付");
            } else if (teamOrderInfo.getBalancePay().compareTo(bijiao) == 0 && teamOrderInfo.getMonthPay().compareTo(bijiao) == 0) {
                trackingOrder.setRemark("抵扣额度支付");
            } else {
                trackingOrder.setRemark("组合支付");
            }
            trackingOrder.setOrderSn(orderSn).setOrderType(2).setOrderStatus(1)
                    .setThing("订单支付")
                    .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername());
            trackingOrderMapper.insert(trackingOrder);
            // 事件表插入数据
            inserEvent(2, 0, "团订订单支付", orderSn, 1, null, null);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 向订单事件表添加记录
     *
     * @param orderType 默认0，面料订单，1个订订单，2团订订单，3成衣订单
     * @param type      默认0日常处理，1紧急事件
     * @param eventName 事件名称
     * @param orderSn   订单编号
     * @param what      事件类型，1支付，2售后
     * @param afterid   售后订单id
     * @param afterCode 售后订单编号
     */
    public void inserEvent(Integer orderType, Integer type, String eventName, String orderSn, Integer what, String afterid, String afterCode) {
        MlccEventRecrodInfo info = new MlccEventRecrodInfo();
        info.setEventName(eventName).setType(type).setOrderType(orderType).setOrderSn(orderSn);
        if (what == 2) {
            // 售后加数据
            info.setAfterorderId(afterid).setAfterorderCode(afterCode);
        }
        eventRecrodInfoMapper.insert(info);
    }

    /**
     * 支付之后更新流水表
     *
     * @param orderid   订单id
     * @param ordertype 订单类型
     */
    public void updatewrater(String orderid, Integer ordertype) {
        QueryWrapper<MlccBusinessWaterInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderid).eq("type", ordertype);
        MlccBusinessWaterInfo waterInfo = businessWaterInfoMapper.selectOne(wrapper);
        if (waterInfo != null) {
            waterInfo.setStatus(2);
            businessWaterInfoMapper.updateById(waterInfo);
        }
    }

    /**
     * 取消订单之后，删除对应的流水
     *
     * @param orderSn 订单编号
     */
    public void delWrater(String orderSn) {
        QueryWrapper<MlccBusinessWaterInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        businessWaterInfoMapper.delete(wrapper);
    }
}
